package cn.lg.soar.system.account.service.impl;

import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.common.util.current.UserContext;
import cn.lg.soar.common.util.data.DataUtil;
import cn.lg.soar.common.util.data.StringUtil;
import cn.lg.soar.core.config.cache.template.ICacheTemplate;
import cn.lg.soar.mvc.log.LogUtils;
import cn.lg.soar.mvc.util.RequestUtils;
import cn.lg.soar.system.account.model.CodeLoginVo;
import cn.lg.soar.system.account.service.ICodeLoginService;
import cn.lg.soar.system.account.service.ILoginService;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class CodeLoginServiceImpl implements ICodeLoginService {

    @Autowired
    private ILoginService loginService;
    @Autowired
    private ICacheTemplate<String, String> cacheTemplate;

    private final static String REDIS_KEY = "login:code:";

    @Override
    public String generate(HttpServletRequest request, String format) {
        String value = RequestUtils.clientId(request);
        String code = DataUtil.byteToBase64(DataUtil.longToBytes(IdWorker.getId()));
        cacheTemplate.put(REDIS_KEY + code, value, Duration.ofMinutes(3));
        if (DataUtil.isValuable(format)) {
            return String.format(format, code);
        }
        return code;
    }

    @Override
    public void handle(CodeLoginVo vo) {
        String key = REDIS_KEY + vo.getCode();
        if (Boolean.TRUE.equals(vo.getAllowable())) {
            // 允许登录
            String str = cacheTemplate.get(key);
            if (StringUtil.isBlank(str)) {
                return;
            }
            cacheTemplate.put(key, str +":"+ UserContext.getUserId(), Duration.ofSeconds(30));
        } else {
            // 不允许登录
            cacheTemplate.delete(key);
        }
    }

    @Override
    public String login(HttpServletRequest request, String code) {
        String str = cacheTemplate.get(REDIS_KEY + code);
        AssertUtil.notEmpty(str, "授权码已失效");
        String value = RequestUtils.clientId(request);
        if (str.equals(value) || !str.contains(":")) {
            return null;
        }
        String[] split = str.split(":");
        AssertUtil.isTrue(split[0].equals(value), "授权码已失效");
        String token = loginService.login(Long.parseLong(split[1]), false);
        LogUtils.log("授权码登录");
        return token;
    }
}
